package fr.bull.learn.thread.monitor;

import java.lang.Thread.State;

import org.apache.log4j.Category;
import org.apache.log4j.Logger;

import fr.bull.learn.thread.task.ComputeTask;
import fr.bull.learn.thread.task.FiboBigInteger;
import fr.bull.learn.thread.task.FiboInt;
import fr.bull.learn.thread.task.FiboTask;
import fr.bull.learn.thread.worker.Worker;

/**
 * This class is for start some Thread.
 * 
 * @author Rouviere-X
 *
 */
public class ThreadMonitor {
	/**
	 * I like log4j.
	 */
	 private Logger log = Logger.getLogger(ThreadMonitor.class);

	 /**
	  * Create 2 worker and start them
	  */
	 public void doIt() {		
		 log.info("I start 2 Thread : look your CPU");
		 Worker w1 = new Worker(new FiboInt());
		 Worker w2 = new Worker(new FiboBigInteger());
		 Worker w3 = new Worker(new ComputeTask());
		 Worker w4 = new Worker(new ComputeTask());
		 w1.start();
		 w2.start();
		 w3.start();
		 w4.start();
		 log.info("ThreadMonitor start Ok");
	}
	 
	private Logger getLogger() {
		return log;
	}

	 /**
	  * How many thread are active ?
	  */
	private void watchThread() {
		int activeCount = Thread.activeCount();
		log.info("There is "+activeCount+" active Thread");
        Thread[] tarray = new Thread[activeCount];
		Thread.enumerate(tarray );
		for (Thread t : tarray){
			log.debug(t.getName() + " is "+t.getState());
		}
        	
	}
	
	 /**
	  * Create a ThreadMonitor an just doIt
	  * @param args
	  */
	 public static void main(String[] args) {  
		 ThreadMonitor tm = new ThreadMonitor();
		 tm.doIt();
		 /**
		  * 3 little turns and go out
		  */
		 for(int i=0; i<3; i++) {
			 tm.watchThread();
			 try {
				Thread.sleep(1000); // sleep 1 sec
			} catch (InterruptedException e) {
				tm.getLogger().error("Who intterupt me ? ", e);
			}
		 }
	 }




}
